<?php

namespace App\Repository\Anchor;

use App\Libs\PhpOffice\Excel;
use App\Models\Anchor\AnchorAuthorModel;
use App\Models\Anchor\AnchorModel;
use App\Models\Anchor\AnchorWorksModel;
use App\Models\Order\OrderExportModel;
use App\Models\Orders\OrdersModel;
use App\Models\Orders\OrdersUserModel;
use App\Repository\BaseRepository;

class AnchorStatsRepository extends BaseRepository
{
//    public $model;

    public function __construct()
    {
//        $this->model = new model();
        parent::__construct();
    }

//    直播统计
    public function stats($params)
    {
        $ModelAnchor = new AnchorModel();
        $ModelAnchorWorks = new AnchorWorksModel();
        $ModelAnchorAuthor = new AnchorAuthorModel();


        $searchAuthorIds = [];
        $anchorWorkWhere = [];
//        主播要特殊处理
        if (isset($params['anchor_id']) && !empty($params['anchor_id'])) {
            $anchorWorkWhere['eq']['a.anchor_id'] = $params['anchor_id'];
        }
//        达人条件
        if (isset($params['author_id']) && !empty($params['author_id'])) {
            $anchorWorkWhere['eq']['a.author_id'] = $params['author_id'];
        }
//        查询条件
        $dateTimeRange = $params['dateRange'];
        if (empty($dateTimeRange) && empty($searchAuthorIds)) {
            $dateTimeRange = [date('Y-m-d H:i:s', time() - 3600 * 24 * 30), date('Y-m-d H:i:s')];
        }
        $anchorWorkWhere['between'] = ['a.created_at' => [$dateTimeRange]];
//        查询开播数据
        $worksRows = [];
        foreach ($ModelAnchorWorks->from($ModelAnchorWorks->getTable() . ' AS a')
                     ->leftJoin($ModelAnchor->getTable() . ' AS b', 'a.anchor_id', '=', 'b.id')
                     ->leftJoin($ModelAnchorAuthor->getTable() . ' AS c', 'a.author_id', '=', 'c.author_id')
                     ->select('a.*', 'b.nickname AS anchor_name', 'c.nickname AS author_name')
                     ->searchWhere($anchorWorkWhere)
                     ->orderByDesc('a.created_at')
                     ->cursor() as $row) {
            $worksRows[] = $row;
        }
        $this->countWorksOrdersData($worksRows);
//        把每场数据汇总
        $result = [];
        foreach ($worksRows as $k => $row) {
            $md5sum = md5($row['anchor_id'] . $row['author_id']);
            if (!isset($result[$md5sum])) {
                $result[$md5sum] = $row;
            } else {
                //                    重复数
                $result[$md5sum]['repeat'] += $row['repeat'];
//                    总时长
                $result[$md5sum]['second'] += $row['second'];
                //            下单总数
                $result[$md5sum]['nums'] += $row['nums'];
                //            订单总数，重复的只算1单
                $result[$md5sum]['sales'] += $row['sales'];
                //            发货数
                $result[$md5sum]['send'] += $row['send'];
                //         激活
                $result[$md5sum]['activat'] += $row['activat'];
                //            充值
                $result[$md5sum]['first'] += $row['first'];
//                推广费用使用每场输入的金额
                $result[$md5sum]['commission'] += $row['cost'];//$row['commission'];
            }
        }
        return array_values($result);
    }

//    每场直播的订单数据,$worksRows必须有author_id/created_at/over_at三个字段
    public function countWorksOrdersData(&$worksRows)
    {
        $ModelOrdersUser = new OrdersUserModel();
        $ModelOrders = new OrdersModel();
        $startWorksTime = '';
        $overWorksTime = '';
        $searchAuthorIds = [];
        foreach ($worksRows as $k => $row) {
            // 找最小的下单开始时间
            if (empty($startWorksTime)) {
                $startWorksTime = $row['created_at'];
            } else {
                if (strtotime($row['created_at']) < strtotime($startWorksTime)) {
                    $startWorksTime = $row['created_at'];
                }
            }
//            找最大的结束时间
            if (empty($row['over_at'])) {
                $row['over_at'] = date('Y-m-d H:i:s');
            }
            if (empty($overWorksTime)) {
                $overWorksTime = $row['over_at'];
            } else {
                if (strtotime($row['over_at']) > strtotime($overWorksTime)) {
                    $overWorksTime = $row['over_at'];
                }
            }
            $anchorWorkCreatedTime = strtotime($row['created_at']);
            $anchorWorkOverTime = empty($row['over_at']) ? time() : strtotime($row['over_at']);
            $second = $anchorWorkOverTime - $anchorWorkCreatedTime;
            $authorId = $row['author_id'];
            $searchAuthorIds[] = $authorId;
//            按每场直播数据来统计
//                    重复数
            $row['repeat'] = 0;
//                    总时长
            $row['second'] = $second;
            //            下单总数
            $row['nums'] = 0;
            //            订单总数，重复的只算1单
            $row['sales'] = 0;
            //            发货数
            $row['send'] = 0;
            //         激活
            $row['activat'] = 0;
            //            充值
            $row['first'] = 0;
            $row['commission'] = 0;
            $worksRows[$k] = $row;
        }
//        查订单数据
        $orderWhere = [];
//            只要已经查到的达人
        $searchAuthorIds = array_unique($searchAuthorIds);
        if (!empty($searchAuthorIds)) {
            if (count($searchAuthorIds) > 1) {
                $orderWhere['in']['a.author_id'] = $searchAuthorIds;
            } else {
                $orderWhere['eq']['a.author_id'] = $searchAuthorIds[0];
            }
        } else {
            $orderWhere['neq']['a.author_id'] = "";
        }
        $orderWhere['between']['a.created_at'] = [$startWorksTime, $overWorksTime];
        //拉黑了的单不算
        $orderWhere['eq']['b.blocking'] = 0;
        //        判断是否是同一个人重复下的单，相同的电话，地址，身份证都可视为同一个人
        $only = [];
        $onlyPhone = [];
        $onlyAddress = [];
        foreach ($ModelOrdersUser->from($ModelOrdersUser->getTable() . ' AS a')
                     ->leftJoin($ModelOrders->getTable() . ' AS b', 'a.orderno', '=', 'b.ordersno')
                     ->select('a.id', 'a.pay_identity', 'a.pay_phone', 'a.post_province', 'a.post_city', 'a.post_area', 'a.post_address', 'a.author_id', 'a.author_name', 'a.author_commission', 'b.created_at', 'b.status', 'b.activat_at', 'b.first_status_at')
                     ->searchWhere($orderWhere)
                     ->orderByDesc('a.id')
                     ->cursor() as $row) {
            $authorId = $row->author_id;
            $ordersTime = strtotime($row->created_at);
//                订单下单时间要在直播时间内才算,判断与$ModelAnchorWorks->getOrdersAuthorInAnchorWorks一样
            foreach ($worksRows as $k => $v) {
                $workStartTime = strtotime($v['created_at']);
                $workOverTime = empty($v['over_at']) ? time() : strtotime($v['over_at']);
                if ($v['author_id'] == $row['author_id'] && ($ordersTime >= $workStartTime && $ordersTime <= $workOverTime)) {
                    if (isset($worksRows[$k]['nums'])) {
                        $worksRows[$k]['nums'] += 1;
                    } else {
                        $worksRows[$k]['nums'] = 1;
                    }
                    //            发货数
                    if (in_array($row->status, [20, 30, 40, 41])) {
                        $worksRows[$k]['send'] += 1;
                    }
//            激活
                    if (!empty($row->activat_at)) {
                        $worksRows[$k]['activat'] += 1;
                    }
//            充值
                    if (!empty($row->first_status_at)) {
                        $worksRows[$k]['first'] += 1;
                    }
                    $hasRepeat = false;
                    //去重后的销量：即一个人只能一单
                    if (isset($only[$authorId]) && in_array($row->pay_identity, $only[$authorId])) {
                        $hasRepeat = true;
                    } else {
                        $only[$authorId][] = $row->pay_identity;
                    }
//            再判断是否是相同电话
                    if (isset($onlyPhone[$authorId]) && in_array($row->pay_phone, $onlyPhone[$authorId])) {
                        $hasRepeat = true;
                    } else {
                        $onlyPhone[$authorId][] = $row->pay_phone;
                    }
//            再判断是否是相同地址
                    $address = md5($row->post_province . $row->post_city . $row->post_area . $row->post_address);
                    if (isset($onlyAddress[$authorId]) && in_array($address, $onlyAddress[$authorId])) {
                        $hasRepeat = true;
                    } else {
                        $onlyAddress[$authorId][] = $address;
                    }
//            佣金,重复的不算
                    if (!$hasRepeat) {
                        $worksRows[$k]['sales'] += 1;
                        $worksRows[$k]['commission'] += $row->author_commission;
                    } else {
                        $worksRows[$k]['repeat'] += 1;
                    }
                    break;
                }
            }
        }
//        return $worksRows;
    }

//查询明细，与下载的数据一起操作
    public function details($request)
    {
        $limit = 0;
        $page = 0;
        if (isset($request['pageNum'])) {
            $page = intval($request['pageNum']);
        }
        if (isset($request['pageSize'])) {
            $limit = intval($request['pageSize']);
        }
//        查询开播数据
        $anchorWorkWhere = [];
//        指定主播
        if (!empty($request['anchor_id'])) {
            $anchorWorkWhere['where']['a.anchor_id'] = $request['anchor_id'];
        }
//        指定达人
        if (!empty($request['author_id'])) {
            $anchorWorkWhere['where']['a.author_id'] = $request['author_id'];
        }
//        指定时间段
        if (!empty($request['dateRange'])) {
            $anchorWorkWhere['between']['a.created_at'] = [$request['dateRange']];
        }
        $worksRows = [];
        $ModelAnchorWorks = new AnchorWorksModel();
        $ModelAnchor = new AnchorModel();
        foreach ($ModelAnchorWorks->from($ModelAnchorWorks->getTable() . ' AS a')
                     ->leftJoin($ModelAnchor->getTable() . ' AS b', 'a.anchor_id', '=', 'b.id')
                     ->select('a.*', 'b.nickname AS anchor_name')
                     ->searchWhere($anchorWorkWhere)
                     ->orderByDesc('a.created_at')
                     ->cursor() as $row) {
            $worksRows[] = $row;
        }
        $ModelOrdersUser = new OrdersUserModel();
        $ModelOrders = new OrdersModel();

        $OrdersTable = $ModelOrders->getTable();
        $OrdersUserTable = $ModelOrdersUser->getTable();
//        查询条件
        if (!empty($request['author_id'])) {
            $where['where']['a.author_id'] = $request['author_id'];
        }
        $time = $request['dateRange'];
        if (!empty($time)) {
            $where['between'] = ['a.created_at' => [$time]];
        }
//        拉黑了的单不算
        $where['eq']['b.blocking'] = 0;
        //        关联查询数据
        if (!empty($where)) {
            $ModelOrdersUser = $ModelOrdersUser->searchWhere($where);
        }
        //        先要总数
        $totalRows = 0;
        if ($page > 0) {
            $totalRows = $ModelOrdersUser->from($OrdersUserTable . ' AS a')->count('a.id');
//            echo $this->getLastSql();
            //        再加上分页查询
            $ModelOrdersUser = $ModelOrdersUser->page($page, $limit);
        }
        $rows = [];
        foreach ($ModelOrdersUser->from($OrdersUserTable . ' AS a')
                     ->leftJoin($OrdersTable . ' AS b', 'a.id', '=', 'b.orders_user_id')
                     ->select('a.id', 'a.orderno', 'a.sku_number', 'a.contact_name', 'a.pay_name', 'a.pay_identity', 'a.author_id', 'a.author_name', 'a.author_commission', 'b.iccid', 'b.created_at', 'b.status', 'b.activat_status', 'b.activat_at', 'b.first_status', 'b.first_money', 'b.first_status_at')
                     ->orderByDesc('a.id')
                     ->cursor() as $row) {
            $worksOpening = $ModelAnchorWorks->getOrdersAuthorInAnchorWorks($worksRows, $row['author_id'], $row['created_at']);
            //订单下单时间要在直播时间内才算
            if (!empty($worksOpening)) {
//                只要指定主播数据
                if (isset($request['anchor_id']) && $request['anchor_id'] != $worksOpening['anchor_id']) {
                    continue;
                }
                // 主播名字
                $row['anchor_name'] = $worksOpening['anchor_name'];
                $row['anchor_id'] = $worksOpening['anchor_id'];
                $row['anchor_created_at'] = $worksOpening['created_at'];
                $row['anchor_over_at'] = $worksOpening['over_at'];
                $row['activat_desc'] = '未激活';
                if ($row['activat_status'] == 1) {
                    $row['activat_desc'] = '已激活';
                }
                $row['first_desc'] = '未首充';
                if ($row['first_status'] == 1) {
                    $row['first_desc'] = '已首充';
                }
//            生产号码
                $row['buy_number'] = $row['iccid'];
                if (empty($row['iccid'])) {
                    $row['buy_number'] = $row['sku_number'];
                }
                $row['status_desc'] = $ModelOrders->getOrderStatusDesc($row['status']);
                $rows[] = $row;
            }
        }
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

//导出下载
    public function downloadExcelPort($id, $params, $name, $type)
    {
        $request = [];
        if (!empty($params)) {
            $request = json_decode($params, true);
//            导出数据，不用分页
            unset($request['pageNum'], $request['pageSize']);
        }
        // var_dump($where);
        $resData = $this->details($request);
        $resData = $resData['data'];
        // var_dump($resData);
        $ExcelClient = new Excel();
        $title = [
            '订单编号',
            '生产号码',
            '用户姓名',
            '主播名称',
            '达人名称',
            '达人编号',
            '开播时间',
            '下播时间',
            '下单时间',
            '收货人',
            '首充时间',
            '充值金额',
            '首充状态',
            '激活时间',
            '激活状态',
            '订单状态',
            '佣金'
        ];
        $excelData = [];
        if (!empty($resData)) {
            foreach ($resData as $key => $v) {
                $excelData[] = [
                    $v['orderno'],
                    $v['buy_number'] ?? '',
                    $v['contact_name'],
                    $v['anchor_name'] ?? '',
                    $v['author_name'] ?? '',
                    $v['author_id'] ?? '',
                    $v['anchor_created_at'] ?? '',
                    $v['anchor_over_at'] ?? '',
                    $v['created_at'],
                    $v['pay_name'],
                    $v['first_status_at'],
                    $v['first_money'],
                    $v['first_desc'],
                    $v['activat_at'],
                    $v['activat_desc'],
                    $v['status_desc'],
                    $v['author_commission']
                ];
            }
        }

        $filename = '/attach/excel/' . $type . '/' . date('Ym') . '/' . $name . date('YmdHis') . $id . '.xlsx';
        $ExcelClient->exportFile($excelData, $title, $filename);
        $ModelExport = new OrderExportModel();
        $ModelExport->where(['id' => $id])->update(['is_run' => 1, 'path' => $filename]);
        return $this->returnMsg(200, '导出成功', ['file' => $filename]);
    }

//    导出数据
    public function getExcelPort($id, $params, $name, $type)
    {
        $request = [];
        if (!empty($params)) {
            $request = json_decode($params, true);

        }
        // var_dump($where);
        $resData = $this->stats($request);
        // var_dump($resData);
        $ExcelClient = new Excel();
        $title = [
            '主播',
            '达人',
            '总时长',
            '总订单',
            '重复单',
            '发货数',
            '下单/时',
            '激活',
            '充值',
            '佣金'
        ];
        $excelData = [];

        if (!empty($resData)) {
            foreach ($resData as $key => $v) {
//                总时长
                $longTimeHour = floor($v['second'] / 3600);
                $avgHour = 0;
                if ($longTimeHour > 0) {
                    $avgHour = floor($v['sales'] / $longTimeHour);
                }
                $excelData[] = [
                    $v['anchor_name'],
                    $v['author_name'],
                    $v['second'],
                    $v['sales'],
                    $v['repeat'],
                    $v['send'],
                    $avgHour,
                    $v['activat'],
                    $v['first'],
                    $v['commission']
                ];
            }
        }

        $filename = '/attach/excel/' . $type . '/' . date('Ym') . '/' . $name . date('YmdHis') . $id . '.xlsx';
        $ExcelClient->exportFile($excelData, $title, $filename);
        $ModelExport = new OrderExportModel();
        $ModelExport->where(['id' => $id])->update(['is_run' => 1, 'path' => $filename]);
        return $this->returnMsg(200, '导出成功', ['file' => $filename]);
    }
}
